import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:image_picker/image_picker.dart';
import 'package:safetymonitor/app/components/toast_widget.dart';
import 'package:safetymonitor/app/core/core.dart';
import 'package:safetymonitor/app/core/ext/widget_extension.dart';
import 'package:safetymonitor/app/core/utils/file_util.dart';
import 'package:safetymonitor/app/core/utils/interface.dart';
import 'package:safetymonitor/app/data/api/file_upload_apis.dart';

///特殊作业-自文件上传样式控件
///[title] 标题
///[onCallBack] 选择回调
///[uploadedFiles] 已上传的文件列表
///[isRequired] 是否必填
///[hintText] 提示文字
///[isEnabled] 是否可编辑
///[isShowDivider] 是否显示分割线
///[isChange] 是否在交接班中
///[maxLines] 最大长度
/// demo:
/// ``` dart
/// CustomFileUploadPage(
///   isRequired: false,
///   isShowDivider: false,
///   isEnabled: false,
///   isChange: isChange,
///   uploadedFiles: [],
///   title: '标题',
///   onCallBack: (value) {},
/// );
/// ```
class CustomFileUploadPage extends StatefulWidget {
  const CustomFileUploadPage({
    required this.title,
    required this.onCallBack,
    this.uploadedFiles,
    this.isRequired = true,
    super.key,
    this.hintText,
    this.isEnabled = true,
    this.isFirst = false,
    this.isShowDivider = true,
    this.isChange = false,
    this.maxLines,
    this.splitCommaInUrl = false,
    this.type = FileType.any,
  });

  final String title;
  final Function(List<String>) onCallBack;
  final List<String>? uploadedFiles;
  final bool isRequired;
  final String? hintText;
  final bool isEnabled;
  final bool isFirst;
  final bool isShowDivider;
  final bool isChange;
  final int? maxLines;
  final bool splitCommaInUrl;
  final FileType type;

  @override
  State<CustomFileUploadPage> createState() => _CustomFileUploadPageState();
}

class _CustomFileUploadPageState extends State<CustomFileUploadPage> {
  List<String> fileUrlList = [];

  @override
  initState() {
    super.initState();
    _initDate();
  }

  /// 初始化数据
  void _initDate() {
    final list = widget.uploadedFiles;
    if (list != null && list.isNotEmpty) {
      if (widget.splitCommaInUrl) {
        fileUrlList.addAll(
          list.fold(<String>[], (p, e) => [...p, ...e.split(',')]),
        );
      } else {
        fileUrlList.addAll(list);
      }
    }
  }

  @override
  void didUpdateWidget(CustomFileUploadPage oldWidget) {
    super.didUpdateWidget(oldWidget);
    //如果发生变化，则清除缓存，以便下次构建时加载新的。 解决initState方法不调用在重建后的问题
    if (oldWidget.uploadedFiles != widget.uploadedFiles) {
      fileUrlList.clear();
      fileUrlList.addAll(widget.uploadedFiles ?? []);
    }
  }

  /// 拍摄图片
  void _takePictures() async {
    final ImagePicker picker = ImagePicker();

    // 拍摄图片
    final XFile? image = await picker.pickImage(source: ImageSource.camera, imageQuality: 30);
    if (image != null) {
      final images = await FileUploadApis.uploadFile(fileUrl: image.path, fileName: '${DateTime.now().millisecondsSinceEpoch}.jpg', isShowLoading: widget.isFirst);
      if (images != '') {
        fileUrlList.add(images);
        //进行回调
        widget.onCallBack(fileUrlList);
        setState(() {});
      } else {
        AppToast.showWarning('上传失败');
      }
    } else {
      // AppToast.showWarning('未选择图片');
    }
  }

  /// 选择文件
  void _selectFile() async {
    final result = await FilePicker.platform.pickFiles(
      // type FileType.custom,
      // allowedExtensions ['pdf', 'doc'],
      // allowMultiple true
      type: widget.type,
      allowedExtensions: widget.type == FileType.custom ? ['png', 'jpg','svg','webp','jpeg','gif','bmp'] : null,
    );
    // 设置不超过10M
    if (result != null && result.files.first.size > 10 * 1024 * 1024) {
      AppToast.showWarning('文件大小不能超过10M');
      return;
    }
    if (result != null) {
      final PlatformFile platformFile = result.files.first;
      final file = await FileUploadApis.uploadFile(fileUrl: platformFile.path!, isShowLoading: widget.isFirst);
      if (file != '') {
        fileUrlList.add(file);
        //进行回调
        widget.onCallBack(fileUrlList);
        setState(() {});
      } else {
        AppToast.showWarning('上传失败');
      }
    } else {
      // AppToast.showWarning('未选择文件');
    }
  }

  ///获取文件列显示
  Widget _getFileView(BuildContext context, int idx) {
    if (idx >= fileUrlList.length) return const SizedBox();
    final url = fileUrlList[idx];

    return Row(
      children: [
        ///显示文件类型图标
        FileUtils.getIcon(url, width: 19.w, height: 19.w),
        AppGaps.hGap10,
        Expanded(
          child: Text(
            url.split('/').lastOrNull ?? '未知文件名',
            style: TextStyle(
              fontSize: 13.sp,
              color: const Color(0xFF5C6DFF),
            ),
          ).clickOnce(
            () {
              //打开文件
              FileUtils.openFile(url.contains('http') ? url : Interface.fileUrl + url);
            },
          ),
        ),
        Visibility(
          visible: widget.isEnabled && !widget.isChange,
          child: Container(
            alignment: Alignment.center,
            child: const Icon(
              Icons.highlight_remove,
              color: Color(0xFFFD6B6B),
            ),
          ).clickOnce(
            () {
              setState(() {
                fileUrlList.remove(url);
                widget.onCallBack(fileUrlList);
              });
            },
          ),
        )
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          children: [
            Visibility(
                visible: widget.isRequired,
                child: Text(
                  '*',
                  style: TextStyle(
                    fontSize: 14.sp,
                    height: 1.2,
                    color: AppColors.meaning_color_danger,
                  ),
                )),
            Text(
              widget.title,
              style: TextStyle(
                fontSize: 14.sp,
                height: 1.1,
                color: AppColors.font_color_black,
              ),
            ),
            Visibility(
              visible: widget.maxLines == null ? true : fileUrlList.length < widget.maxLines!,
              child: Expanded(
                child: SizedBox(
                  // height: 50.w,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Text(
                        widget.isEnabled
                            ? widget.hintText ?? '请上传'
                            : fileUrlList.isEmpty
                                ? '暂无'
                                : '',
                        style: TextStyle(
                          fontSize: 14.sp,
                          height: 1.2,
                          color: AppColors.text_grey,
                        ),
                      ),
                      Visibility(
                          visible: widget.isEnabled,
                          child: Row(
                            children: [AppGaps.hGap6, Icon(Icons.arrow_forward_ios, size: 14.sp, color: AppColors.text_grey)],
                          )),
                    ],
                  ),
                ).clickOnce(() {
                  if (fileUrlList.isNotEmpty && widget.isFirst) {
                    AppToast.showWarning('上传文件的数量不能超过1个！');
                    return;
                  }

                  if (!widget.isEnabled) return;
                  showCupertinoModalPopup(
                    context: context,
                    builder: (context) {
                      return CupertinoActionSheet(
                        actions: [
                          CupertinoActionSheetAction(
                            child: const Text('拍照'),
                            onPressed: () {
                              Navigator.of(context).pop();
                              _takePictures();
                            },
                          ),
                          CupertinoActionSheetAction(
                            child: const Text('从手机中选择'),
                            onPressed: () {
                              Navigator.of(context).pop();
                              _selectFile();
                            },
                          ),
                        ],
                        cancelButton: CupertinoActionSheetAction(
                          onPressed: Navigator.of(context).pop,
                          child: const Text('取消'),
                        ),
                      );
                    },
                  );
                }),
              ),
            ),
          ],
        ),
        Visibility(visible: fileUrlList.isNotEmpty, child: AppGaps.vGap10),
        // ListView.separated(
        //   itemCount: fileUrlList.length,
        //   shrinkWrap: true,
        //   physics: const NeverScrollableScrollPhysics(),
        //   itemBuilder: _getFileView,
        //   separatorBuilder: (_, __) => AppGaps.vGap8,
        // ),
        Column(children: fileUrlList.asMap().entries.map((e)=>_getFileView(context,e.key)).toList() .fold<List<Widget>>([], (previous, current) {
          if (previous.isNotEmpty) {
            previous.add( SizedBox(height: 8.w)); // 添加间距
          }
          previous.add(current);
          return previous;
        }),),
        Visibility(visible: fileUrlList.isNotEmpty, child: AppGaps.vGap10),
        Visibility(visible: widget.isShowDivider, child: Divider(height: 1.w, color: AppColors.bg_color_grey)),
      ],
    );
  }
}
